#!/usr/bin/env ruby
#
# Created by Jerry Luk on 2008-05-09
# Copyright (c) 2008. All rights reserved.

# Represents the Google Contact Data
module Google
  class GContactList < GData
    attr_accessor :contacts
    
    def initialize(data=RSS::Atom::Feed.new)
      super(data)
    end
    
    def contacts
      @contacts ||= @atom.entries.map { |c| GContact.new(c) } if @atom
    end
  end
  
  class GContact < GData
    
    INFORMATION_TYPE = {
      :home   => "http://schemas.google.com/g/2005#home",
      :mobile => "http://schemas.google.com/g/2005#mobile",
      :work   => "http://schemas.google.com/g/2005#work"
    }
    
    def email
      if @atom and @atom.gd_emails
        primary_email = @atom.gd_emails.detect { |e| e.primary == 'true' }
        primary_email ||= @atom.gd_emails.first
        primary_email.address
      end
    end
    
    def emails
      @atom.gd_emails if @atom
    end
    
    def name
      title
    end
    
    def name=(new_name)
      self.title = new_name
    end
    
    def phone_number
      if @atom and @atom.gd_phone_numbers
        primary_phone = @atom.gd_phone_numbers.detect { |p| p.primary == 'true' }
        primary_phone ||= @atom.gd_phone_numbers.first
        primary_phone.content
      end
    end
    
    def phone_numbers
      @atom.gd_phone_numbers if @atom
    end
    
    def address
      @atom.gd_postal_addresses.first.content if @atom and @atom.gd_postal_addresses
    end
    
    def addresses
      @atom.gd_postal_addresses if @atom
    end
    
    def im
      @atom.gd_ims.first.address if @atom and @atom.gd_ims
    end
    
    def ims
      @atom.gd_ims if @atom
    end
  end
end